package com.ruoyi.system.xcenter.Scheduled;


import cn.hutool.http.HttpUtil;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.system.domain.DataxEndPoint;
import com.ruoyi.system.mapper.DataxEndPointMapper;
import com.ruoyi.system.xcenter.exception.DataXException;
import com.ruoyi.system.xcenter.utils.RSAUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;

@Component("jobService")
public class ScheduledJob {
    @Autowired
    private DataxEndPointMapper dataxEndPointMapper ;
    /**
     * 定时心跳请求
     * i:0 发送心跳，1不发送，2 发送心跳和车位
     * @param i
     */
    public void heartThrob(Integer i) throws Exception {
        DataxEndPoint dataxEndPoint =new DataxEndPoint();
        //isHeart为0,需要发送心跳请求
        dataxEndPoint.setIsHeart(i);
        List<DataxEndPoint> list= dataxEndPointMapper.selectDataxEndPointList(dataxEndPoint);
        for(DataxEndPoint dataxEndPointTemp:list){
           postHeartThrob(dataxEndPointTemp);
       }

    }


    /**
     * 根据停车场编号发送心跳请求
     * @param dataxEndPointTemp
     * @throws Exception
     */
    public static void postHeartThrob(DataxEndPoint dataxEndPointTemp) throws Exception {
        String suffix="/heartThrob";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accessName", dataxEndPointTemp.getAccessname());
//        System.out.println(JSON.marshal(dataxEndPointTemp.getParkNo()));
        JSONObject jsonParkNo=new JSONObject();
        jsonParkNo.put("parkpotId",dataxEndPointTemp.getParkNo());

        if(dataxEndPointTemp.getIsHeart()==2){
            jsonParkNo.put("freeParklotCount",new Random().nextInt(5) + 40);
        }
        String dataStr = RSAUtil.encryptByPrivateKey(JSON.marshal(jsonParkNo), dataxEndPointTemp.getAccountPwdUp());
        jsonObject.put("data", dataStr);
        jsonObject.put("sign", RSAUtil.sign(dataStr, dataxEndPointTemp.getAccountPwdUp()));
        String res = HttpUtil.post(dataxEndPointTemp.getDataUploadUrl() + suffix, JSON.marshal(jsonObject),6000);
        System.out.println(res);
        Integer code = JSON.unmarshal(res, JSONObject.class).getInt("result");
        if(code!=0){
            throw new DataXException(res);
        }

    }


}
